package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import org.apache.http.HttpResponse;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.resource.HttpResource;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

/**
 * 处理文件上传下载
 */
@RestController
@RequestMapping("common")
public class CommonController {

    @Value("${reggie.path}")
    private String BASE_PATH;
    /**
     * 文件上传
     * @param file
     * @return
     */
    @PostMapping("upload")
    public R<String>upload(MultipartFile file) throws IOException {//MultipartFile:表示文件上传文件临时文件
        //1.判断文件夹是否存在
        File dirFile = new File(BASE_PATH);
        //判断文件是否存在
        if (!dirFile.exists()){
            //说明文件不存在,就需要创建文件夹
            dirFile.mkdir();
        }
        //2.生产唯一UUID文件名称
        String uuid = UUID.randomUUID().toString();

        //截取原始文件名后缀
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        String uuidFileName=uuid + suffix;

        //3.将文件存到指定路径
       file.transferTo(new File(BASE_PATH+"/"+uuidFileName));

        //4.响应文件数据
        return R.success(uuidFileName);
    }

    /**
     * 文件下载
     * @param name
     * @param response
     * @throws IOException
     */
    @GetMapping("download")
    public void download(String name, HttpServletResponse response) throws IOException {
        //准备输入流
        FileInputStream fileInputStream = new FileInputStream(BASE_PATH + "/" + name);
        //输出流 response
        ServletOutputStream outputStream = response.getOutputStream();
        //输入流和输出流对接,输入流:服务器文件,输出流:response
        IOUtils.copy(fileInputStream,outputStream);
        fileInputStream.close();

    }

}
